import API from './index.js'
import Cookies from 'js-cookie'
import store from "../store";

/**
 * 获取令牌
 */
export async function getToken() {

    let token = Cookies.get("RSS-TOKEN");
    let refreshToken = store.getters.refreshToken;

    if (token != null && sessionStorage.getItem("RSS-USER") == null) {
        Cookies.remove("RSS-TOKEN");
        token = Cookies.get("RSS-TOKEN");
    }
    if ((token == null && refreshToken != null)) {
        let ret = await API.refresh(refreshToken);
        if (ret.status) {
            // 保存 用户 和 权限列表 到 store 中
            store.commit("storeUserAndToken", {
                user: ret.user,
                token: ret.accessToken,
                exp: ret.exp,
                refresh: ret.refreshToken,
                remember: localStorage.getItem("RSS-REFRESH-TOKEN") != null
            });
            token = ret.accessToken ;
        } else { // 如果接口调用失败，将接口的失败信息抛出去
            let error = new Error("刷新接口调用失败");
            error.response = data;
            throw error;
        }
    }
    return token ;
}

